﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class ComponentSearcher : EditorWindow
{
    private GameObject targetObject;
    private string[] componentNames = { "编辑 UIlabel", "编辑 UISprite", "编辑 _StencilRef" };
    private int selectedIndex = 0;
    private Material material;
    private Shader shader;
    private int stencilRef;

    [MenuItem("Tools/Component Searcher And Edit")]
    public static void ShowWindow()
    {
        GetWindow<ComponentSearcher>("Component Searcher");
    }

    void OnGUI()
    {
        GUILayout.Label("Find Component in GameObject", EditorStyles.boldLabel);

        targetObject = (GameObject)EditorGUILayout.ObjectField("编辑对象", targetObject, typeof(GameObject), true);
        selectedIndex = EditorGUILayout.Popup("编辑类型", selectedIndex, componentNames);
        if (selectedIndex == 0)
        {
            material = (Material)EditorGUILayout.ObjectField("material", material, typeof(Material), true);
        }
        else if (selectedIndex == 1)
        {
            shader = (Shader)EditorGUILayout.ObjectField("shader", shader, typeof(Shader), true);
        }
        else if (selectedIndex == 2)
        {
            stencilRef = EditorGUILayout.IntField("_StencilRef", stencilRef);
        }
        if (GUILayout.Button("Search"))
        {
            if (targetObject != null)
            {
                if (selectedIndex == 0)
                {
                    UILabel[] components = targetObject.GetComponentsInChildren<UILabel>();
                    foreach (UILabel component in components)
                    {
                        component.material = material;
                    }
                }
                else if (selectedIndex == 1)
                {
                    UISprite[] components = targetObject.GetComponentsInChildren<UISprite>();
                    foreach (UISprite component in components)
                    {
                        component.mShader = shader;
                    }
                }
                else if (selectedIndex == 2)
                {
                    UILabel[] components = targetObject.GetComponentsInChildren<UILabel>();
                    foreach (UILabel component in components)
                    {
                        component.stencilRef = stencilRef;
                    }
                    UISprite[] components2 = targetObject.GetComponentsInChildren<UISprite>();
                    foreach (UISprite component in components2)
                    {
                        component.stencilRef = stencilRef;
                    }
                }
            }
        }
    }
}
